<script setup>
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { computed, nextTick, ref, watch } from 'vue'

import { fetchGnssSensorHistoryData } from '@/api/manager/dataManage/deviceManage.js'

let _chart

defineOptions({
  name: 'SensorData',
})

const props = defineProps({
  pkid: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['close'])

const dialogVisible = ref(false)

const timeDuration = [
  {
    label: '近3天',
    value: 'threeDays',
  },
  {
    label: '近1周',
    value: 'oneWeek',
  },
  {
    label: '近15天',
    value: 'fifteenDays',
  },
]

const currentTimeDuration = ref('threeDays')

const chartData = ref([])

const fetchHistoryData = () => {
  const today = dayjs()
  let startDay = ''
  switch (currentTimeDuration.value) {
    case 'threeDays':
      startDay = today.subtract(3, 'day')
      break
    case 'oneWeek':
      startDay = today.subtract(7, 'day')
      break
    case 'fifteenDays':
      startDay = today.subtract(15, 'day')
      break
    default:
      break
  }
  fetchGnssSensorHistoryData({
    pkid: props.pkid,
    beginTime: startDay.format('YYYY-MM-DD') + ' 00:00:00',
    endTime: today.format('YYYY-MM-DD') + ' 23:59:59',
  }).then((res) => {
    if (res.success) {
      chartData.value = res.data
    } else {
      chartData.value = []
      ElMessage.error(res.message || '查询数据失败')
    }
  })
}

const afterOpened = () => {
  if (!_chart) {
    _chart = echarts.init(document.getElementById('sensor-data-chart'))
  }
  nextTick(() => {
    _chart.setOption(chartOptions.value)
    _chart.resize()
    fetchHistoryData()
  })
}

const handleClose = () => {
  dialogVisible.value = false
}

const chartOptions = computed(() => {
  return {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['X轴偏移量', 'Y轴偏移量', 'Z轴偏移量'],
    },
    grid: {
      left: '5%',
      right: '4%',
      top: '10%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: chartData.value.map((item) =>
        dayjs(item.collectingTime).format('YYYY-MM-DD HH:mm:ss'),
      ),
      axisLabel: {
        formatter: (value) => value.replace(' ', '\n'),
        margin: 16,
      },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} mm',
      },
    },
    series: [
      {
        name: 'X轴偏移量',
        type: 'line',
        data: chartData.value.map((item) => item.deviceData),
        symbol: 'none',
        smooth: true,
      },
      {
        name: 'Y轴偏移量',
        type: 'line',
        data: chartData.value.map((item) => item.sinkingData),
        symbol: 'none',
        smooth: true,
      },
      {
        name: 'Z轴偏移量',
        type: 'line',
        data: chartData.value.map((item) => item.sinkingAccumulation),
        symbol: 'none',
        smooth: true,
      },
    ],
  }
})

watch(currentTimeDuration, () => {
  fetchHistoryData()
})

watch(dialogVisible, (val) => {
  if (!val) {
    chartData.value = []
  }
})

watch(chartOptions, (val) => {
  console.log('')
  _chart?.setOption(val)
})

defineExpose({ dialogVisible })
</script>

<template>
  <el-dialog
    class="custom-dialog"
    v-model="dialogVisible"
    title="历史数据"
    width="600px"
    @close="handleClose"
    @opened="afterOpened"
  >
    <div class="sensor-data-content">
      <div class="sensor-data-content-left">
        <el-radio-group v-model="currentTimeDuration">
          <div class="radio-items">
            <el-radio
              v-for="item in timeDuration"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</el-radio
            >
          </div>
        </el-radio-group>
      </div>

      <el-divider direction="vertical" />

      <div class="sensor-data-content-right">
        <div id="sensor-data-chart" />
      </div>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.sensor-data-content {
  height: 300px;
  display: flex;
  padding: 0;

  &-left {
    .radio-items {
      display: flex;
      flex-direction: column;
    }
  }

  .el-divider {
    height: 100%;
  }

  &-right {
    flex: 1;

    #sensor-data-chart {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
